﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ReportFlat.Common;
using ReportFlat.DataAccess;
using System.Collections;


namespace ReportFlat.Web.server.business
{
    public class Stock : BaseHandler
    {
        /// <summary>
        /// 保存
        /// </summary>
        [UseDB(Transaction = true)]
        public void Save()
        {
            c_stock obj = ToPo<c_stock>();
            if (obj.FID == 0)
            {
                dao.Save(obj);
            }
            else
            {
                dao.Update(obj);
            }
            jsonResult = JSONHelper.SuccessJson;
        }

        /// <summary>
        /// 删除
        /// </summary>
        [UseDB(Transaction = true)]
        public void Delete()
        {
            dao.Delete(new c_stock() { FID = Convert.ToInt32(Request["FID"]) });
            jsonResult = JSONHelper.SuccessJson;
        }

          /// <summary>
          /// 删除(多选)
          /// </summary>
         [UseDB(Transaction = true)]
          public void DeleteAll()
          {
             dao.ExcuteByHSql("delete from c_stock where FID in (" + Request["FIDS"].ToString() + ")");
             jsonResult = JSONHelper.SuccessJson;
          }

        /// <summary>
        /// 获取列表
        /// </summary>
        [UseDB]
        public void GetList()
        {
            int start = int.Parse(Request["start"]);
            int limit = int.Parse(Request["limit"]);
            string sWhere = Request["where"];
            if (!GMLogin.isAdminUser())
            {
                sWhere = sWhere.and("FStonehouseID in (select FID from c_stonehouse where FManager=" + GMLogin.UserID+")");
            }
            int rowCount;
            IList<c_stock> list = dao.GetList<c_stock>(out rowCount, sWhere, "", start, limit);
            object sum = dao.GetFieldValue("select sum(FQuantity) from c_stock where 1=1 ".and(sWhere));

            jsonResult = JSONHelper.ToSucJson((IList)list, rowCount, new{FQuantity=sum});
        }

        /// <summary>
        /// 获取单条数据
        /// </summary>
        [UseDB]
        public void GetSingle()
        {
            string sWhere = Request["where"];
            c_stock data = dao.Get<c_stock>(sWhere);
            jsonResult = JSONHelper.ToSucJson("data", data);
        }

        /// <summary>
        /// 获取下拉列表
        /// </summary>
        [UseDB]
        public void GetOptions()
        {
            IList<c_stock> list = dao.GetList<c_stock>();
            jsonResult = JSONHelper.ToSucJson("options", (IList)list);
        }



        /// <summary>
        /// 下载Excel
        /// </summary>
        [UseDB]
        public void ExportExcel()
        {
            string sWhere = this.context.Server.UrlDecode(Request.Params["where"].ToString());
            int rowCount;
            if (!GMLogin.isAdminUser())
            {
                sWhere = sWhere.and("FStonehouseID in (select FID from c_stonehouse where FManager=" + GMLogin.UserID + ")");
            }
            IList<c_stock> list = dao.GetList<c_stock>(out rowCount, sWhere, "", 0, 10000);
            CreateExcel(list);
        }

        private void CreateExcel(IList<c_stock> list)
        {
            String fileName = "系统库存" + DateTime.Now.ToString("yyyyMMdd") + ".csv";
            String[] Columns = {"序号","仓库名称", "产品名称", "规格及型号",
                                 "单位","数量", "备注"};
            HttpResponse resp;
            resp = this.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            string colHeaders = "", ls_item = "";

            int i = 0;
            int cl = Columns.Length;

            //取得数据表各列标题，各标题之间以t分割，最后一个列标题后加回车符 
            for (i = 0; i < cl; i++)
            {
                if (i == (cl - 1))//最后一列，加n
                {
                    colHeaders += Columns[i] + "\r\n";
                }
                else
                {
                    colHeaders += Columns[i] + ",";
                }

            }
            resp.Write(colHeaders);
            //向HTTP输出流中写入取得的数据信息 
            //String[] Columns = {"序号","仓库名称", "产品名称", "规格及型号",
            //                    "单位","数量", "备注"};
            //逐行处理数据   
            int rownum = 1;
            decimal sum = 0;
            foreach (c_stock row in list)
            {
                ls_item += rownum.ToString() + ",";
                ls_item += FormatHtmlStr(row.StonehouseName) + ",";
                ls_item += FormatHtmlStr(row.ProductName) + ",";
                ls_item += FormatHtmlStr(row.ProductModel) + ",";
                ls_item += FormatHtmlStr(row.ProductUnit) + ",";
                ls_item += FormatHtmlStr(row.FQuantity) + ",";
                ls_item += FormatHtmlStr(row.FNote) + "\r\n";
                resp.Write(ls_item);
                ls_item = "";
                rownum++;
                sum = sum + row.FQuantity;
            }

            //合计行输出
            resp.Write(",合计,,,,"+sum+",");
            //resp.End();
        }

        private string FormatHtmlStr(object s)
        {
            if (s == null)
            {
                return "";
            }
            string result = s.ToString();
            result = result.Replace("<font color=blue>", "");
            result = result.Replace("</font>", "");
            result = result.Replace("</font>", "");
            result = result.Replace(",", ";");
            result = result.Replace("，", ";");
            result = result.Replace("<br>", "     ");
            result = result.Replace("\r\n", "     ");
            result = result.Replace("\n", "     ");
            return result.ToString();
        }
      
    }
}